<script setup lang="ts">
import type { CourseScheduleLessonDateGroup, LessonGroupLessonItem, LessonRequestParams } from '@/api/types/lesson'
import { handleApiError } from '@/api'
import { lessonApi } from '@/api/modules/lesson'
import Empty from '@/components/Empty.vue'
import { LessonCourseType } from '@/enums/course'
import { Pagination } from '@/enums/pageList'
import { formatLessonInfo, mergeLessonResponseData } from '@/pages/tabBar/courseSchedule/format'
import { useCurrentStudentInfoStore } from '@/stores/modules/useCurrentStudentInfoStore'
import { navigateTo } from '@/utils/navigation'
import { onReachBottom, onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import RootTabBar from '../components/RootTabBar.vue'
import CourseLessonItem from './components/CourseLessonItem.vue'
import LessonStatusTabs from './components/LessonStatusTabs.vue'
import ScheduleFilter from './components/ScheduleFilter.vue'
import ScheduleHeader from './components/ScheduleHeader.vue'
import StartClassDialog from './components/StartLessonDialog.vue'
import '@/scss/courseSchedule.scss'

const studentInfoStore = useCurrentStudentInfoStore()
const lessons = ref<CourseScheduleLessonDateGroup[]>([])
const loading = ref(false)
const hasMore = ref(true)
const startLessonDialogRef = ref()
const currentLessonItem = ref<LessonGroupLessonItem>()

const searchParams = ref<LessonRequestParams>({
  size: Pagination.DEFAULT_PAGE_SIZE,
  cursor: 0,
  filters: {
    status: 1,
    type: null,
    student: '',
    lessonDate: '',
  },
})

const isEmpty = computed(() => {
  return lessons.value.length === 0
})

const courseTypeRoutes: Record<number, string> = {
  [LessonCourseType.EXPERIENCE]: '/pages/experience/welcome',
  [LessonCourseType.TRAINING]: '/pages/student/unitInfo/index',
  [LessonCourseType.REVIEW]: '/pages/wordStudy/reviewCheck?type=review',
  // 默认路由
  0: '/pages/student/courseList/index',
}

function handleCourseClick(lesson: LessonGroupLessonItem) {
  const { student, lessonId, type } = lesson

  studentInfoStore.setStudentId(student.id)
  studentInfoStore.setLessonId(lessonId)
  studentInfoStore.fetchStudentInfo()

  currentLessonItem.value = lesson

  const url = courseTypeRoutes[type] || courseTypeRoutes[0]
  // TODO 这里 不一定 需要弹窗， 根据当前课时状态 判断是否需要
  if (type === LessonCourseType.TRAINING) {
    startLessonDialogRef.value.open(formatLessonInfo(lesson))
    return
  }

  navigateTo({
    url,
    params: { studentId: student.id, lessonId },
  })
}

async function loadCourses() {
  if (loading.value || !hasMore.value) {
    return
  }

  if (searchParams.value.cursor === 0) {
    lessons.value = []
  }

  loading.value = true
  const [error, result] = await lessonApi.getLessonList(searchParams.value)
  loading.value = false

  if (error) {
    return handleApiError(error)
  }

  hasMore.value = result.data.hasMore
  searchParams.value.cursor = result.data.nextCursor
  lessons.value = mergeLessonResponseData([...lessons.value, ...result.data.list])
}

function updateSearchParams(payload: any) {
  searchParams.value = {
    ...searchParams.value,
    filters: {
      ...searchParams.value.filters,
      lessonDate: payload.currentDate,
      type: payload.currentType,
      student: payload.searchText,
    },
    cursor: 0,
  }
  hasMore.value = true
}

async function onSearchChange(payload: any) {
  updateSearchParams(payload)
  loadCourses()
}

async function onTabChange() {
  updateSearchParams({})
  hasMore.value = true
  loadCourses()
}

function onStartLesson() {
  const currentLessonItemObj = currentLessonItem.value!
  const url = courseTypeRoutes[currentLessonItemObj.type] || courseTypeRoutes[0]
  navigateTo({
    url,
    params: { studentId: currentLessonItemObj.student.id, lessonId: currentLessonItemObj.lessonId },
  })
}

onShow(() => {
  updateSearchParams({})
  loadCourses()
})

onReachBottom(() => {
  loadCourses()
})
</script>

<template>
  <view class="index-container">
    <StartClassDialog ref="startLessonDialogRef" @start-lesson="onStartLesson" />

    <ScheduleHeader />
    <!-- <StatsCard /> -->
    <ScheduleFilter @search-change="onSearchChange" />

    <view class="course-section">
      <LessonStatusTabs v-model="searchParams.filters.status" @change="onTabChange" />

      <Empty v-if="isEmpty" />

      <view class="course-list">
        <view v-for="(course, index) in lessons" :key="index">
          <view class="mb-10 date">
            {{ course.lessonDate }}
          </view>

          <CourseLessonItem
            v-for="lesson in course.lessons"
            :key="lesson.id"
            :lesson="lesson"
            @click="handleCourseClick(lesson)"
          />
        </view>

        <view v-if="loading">
          <uv-load-more status="loading" />
        </view>
      </view>
    </view>

    <RootTabBar :value="0" />
  </view>
</template>
